#include "vbomanager.h"

VBOManager::VBOManager(short x, short y, short z)
    :vbuf(QGLBuffer::VertexBuffer), ibuf(QGLBuffer::IndexBuffer)
//: inarr(CHUNK_SIZE * CHUNK_SIZE * CHUNK_SIZE * 12)//not 24. max is half the faces with proximity face removal
{
    vbuf.create();
    vbuf.bind();
    vbuf.setUsagePattern(QGLBuffer::StaticDraw);
    vbuf.allocate(sizeof(vboVoxel)*CHUNK_SIZE * CHUNK_SIZE * CHUNK_SIZE);
    vbuf.release();


   ibuf.create();
   ibuf.bind();
   ibuf.setUsagePattern(QGLBuffer::StaticDraw);
   ibuf.allocate(CHUNK_SIZE * CHUNK_SIZE * CHUNK_SIZE * 12 * sizeof(unsigned short));
   ibuf.release();
   icount=0;

}

void VBOManager::addVoxel(voxel& v, int x, int y, int z){
    if(!v.draw() || !v.drawFaces())return;
    unsigned short index=vector_to_index(x,y,z);
    unsigned short i=index * 8;

    vboVoxel temp;
    temp.setCoords(x,y,z);
    temp.setColor(v.getColor());
    writeVBOVoxel(index,temp);

    if(v.drawTop()){
        writeVBOIndex(i+7);
        writeVBOIndex(i+6);
        writeVBOIndex(i+2);
        writeVBOIndex(i+3);

    }

    if(v.drawBottom()){
        writeVBOIndex(i+5);
        writeVBOIndex(i+1);
        writeVBOIndex(i+0);
        writeVBOIndex(i+4);
    }

    if(v.drawFront()){
        writeVBOIndex(i+5);
        writeVBOIndex(i+7);
        writeVBOIndex(i+3);
        writeVBOIndex(i+1);
    }

    if(v.drawBack()){
        writeVBOIndex(i+0);
        writeVBOIndex(i+2);
        writeVBOIndex(i+6);
        writeVBOIndex(i+4);
    }

    if(v.drawLeft()){
        writeVBOIndex(i+1);
        writeVBOIndex(i+3);
        writeVBOIndex(i+2);
        writeVBOIndex(i+0);
    }

    if(v.drawRight()){
        writeVBOIndex(i+4);
        writeVBOIndex(i+6);
        writeVBOIndex(i+7);
        writeVBOIndex(i+5);
    }
}

void VBOManager::render(){
    //printf("Rendering");
    //fflush(stdout);

    vbuf.bind();
    glColorPointer(3,GL_UNSIGNED_BYTE, sizeof(vertex),BUFFER_OFFSET(0));
    glNormalPointer(GL_BYTE, sizeof(vertex),BUFFER_OFFSET(sizeof(colour)));
    glVertexPointer(3,GL_SHORT, sizeof(vertex),BUFFER_OFFSET(sizeof(colour)+sizeof(char)*3));
    vbuf.release();

    ibuf.bind();
    glDrawElements(GL_QUADS,icount,GL_UNSIGNED_SHORT,BUFFER_OFFSET(0));
    ibuf.release();
}

VBOManager::~VBOManager(){
    vbuf.destroy();
    ibuf.destroy();
}

